package books4africa

import grails.plugins.springsecurity.*
import org.springframework.dao.DataIntegrityViolationException
import org.codehaus.groovy.tools.shell.commands.RegisterCommand
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails

class TeacherController {
    def scaffold = true
	def userDetailsService
	def springSecurityService
	
    def index() {
        redirect(action: list)
    }
    def tcreate ={
	redirect(action: create)
}
	def currentUser(){
		Teacher.get(springSecurityService.principal.id)
	
	}
	
	def login = { }
	
	def doLogin = {
		def teacher= Teacher.findWhere(username:params['username'],
			password:params['password'])
			session.teacher = teacher
			
			
		UserDetails userDetails =  userDetailsService.loadUserByUsername('username', true)
			println="user datails = $userDetails"
			 
	
		if(teacher){
		//	redirect(uri: "/profile/profileView", params: donor);
			redirect(controller: 'profileView',action: 'view', params: [name: session.name])
		}else{
		//flash.message= "Invalid login"
		//return [donor: donor ]
			redirect(uri: "/");
	}
		
  }
	
	def register = {
		if(!params.register) return
		
		def role = Role.findByAuthoruty("ROLE_USER")
		if(!role){
			teacher.password = null
			flash.message = "Default Role not found."
			return
		}
		//if user has errors
		//if user is not saved
		UserRole.create donor, role
		
	}
	
	def changePassword = {
		if(!params.submit){
			return [teacher: currentUser()]
		}
		String pass1 = params.password
		String pass2 = params.repeatPassword
		def teacher = currentUser()
		if(pass1 != pass2){
			teacher.password = ""
			flash.message = "Error: Passwords Did Not Match"
		}
		teacher.password = pass1
		if(teacher.validate()){
			teacher.save()
			redirect(controller: "login", action: "auth", params: [username: teacher.username])
		}else{
			teacher.password = ""
			return [teacher: teacher]
		}
	}
	
}
